<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/13
 * Time: 11:23
 */

namespace app\mec\controller;

use app\mec\model\MechanismMember as MechanismMemberModel;//机构管理员
use app\mec\model\Mechanism as MechanismModel;
use think\Db;//机构

class Mechanismuser extends Base
{
    /**
     * 机构管理员列表展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $params = input('param.');
            $wheres = [];
            //管理员账号模糊查询
            if(isset($params['key']) && $params['key'] != '')
            {
                $wheres['m.mechanism_member_phone|m.mechanism_member_name'] = ['like', "%" . $params['key'] . "%"];
            }
            $ids = $this->mechanism_id;
            $wheres['m.mechanism_id'] = ['IN', $ids];
            $page = input('page') ? input('page') : 1;
            $limits = input('limit') ? input('limit') : 10;// 获取总条数;
            $field1 = 'm.id, m.mechanism_member_phone, m.mechanism_member_name, m.mechanism_member_img, m.last_login_time,
            m.mechanism_member_status, um.mechanism_name';
            $mechanismMemberModel = new MechanismMemberModel();
            $lists = $mechanismMemberModel->getMechanismMemberList($field1, $wheres, $page, $limits);
            $count = $mechanismMemberModel->countNum($wheres);

            foreach($lists as $k=>$v)
            {
                if(!empty($lists[$k]['last_login_time'])){
                    $lists[$k]['last_login_time'] = date('Y-m-d H:i',$v['last_login_time']);
                }else{
                    $lists[$k]['last_login_time'] = "";
                }
            }
            return json(['code'=>0,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        return $this->fetch("mechanismuser/index");
    }
    
    /**
     * 添加机构管理员
     * @return mixed|\think\response\Json
     */
    public function mechanismuserAdd()
    {
        if(request()->isAjax()){
            extract(input());
            $param = input('post.');
            if(!isset($mechanism_member_status)){
                $param['mechanism_member_status'] = 2;
            }
            $mechanismMemberModel = new MechanismMemberModel();
            $pwd = $param['mechanism_member_password'];
            $param['mechanism_member_password'] = md5($param['mechanism_member_password']);
            $base64url = $param['mechanism_member_img'];
            //匹配出图片的格式
            $base64url = str_replace(' ', '+', $base64url);
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64url, $result)){
                $type = $result[2];
                $new_file = ROOT_PATH . 'public' . DS . 'uploads/face/'.date('Ymd',time())."/";
                if(!file_exists($new_file)){
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($new_file, 0700);
                }
                $new_file = $new_file.time().".{$type}";
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64url)))){
                    $new = md5(time());
                    //压缩图片
                    image_png_size_add($new_file,ROOT_PATH . 'public' . DS . 'uploads/face/'.date('Ymd',time())."/".$new.".{$type}");
                    $url =  "http://".$_SERVER['HTTP_HOST'];
                    $file_name = $url."/uploads/face/".date('Ymd',time())."/".$new.".{$type}";
                    $param['mechanism_member_img'] = $file_name;
                    //删除未压缩前图片
                    unlink($new_file);
                }else{
                    return json(['code'=>100,'msg'=>"上传失败"]);
                }
            }
            $param['create_time'] = time();
            $flag = $mechanismMemberModel->insertMechanismMember($param);
            if($flag){
                //TODO:发送短信提醒
                $templateid = config('yzx')['allow'];
                //机构名
                $mechanism_name = Db::table('up_mechanism')->where('mechanism_id', $param['mechanism_id'])->value('mechanism_name');
                $str = $mechanism_name.','.$param['mechanism_member_phone'].','.$pwd;//参数  机构名,账号,密码
                try{
                    YzxSms($templateid, $str, $param['mechanism_member_phone'], '');//发送短信
                }catch(\Exception $e){
        
                }
            }
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }else{
            $ids = $this->mechanism_id;//获取本机构和下级机构的id
            $where['mechanism_id'] = ['IN', $ids];
            $mechanismModel = new MechanismModel();
            $mechanismInfo = $mechanismModel->getMechanismInfo($where);
            $mechanism_pid_id = Db::table('up_mechanism')->where('mechanism_id', session('mmid'))->value('mechanism_pid_id');
            $mechanismInfo = getCate($mechanismInfo, $mechanism_pid_id);//无限分类
            $this->assign('mechanismInfo', $mechanismInfo);
            return $this->fetch('mechanismuser/mechanismuseradd');
        }
    }
    
    /**
     * 编辑机构管理员
     * @return \think\response\Json
     */
    public function mechanismuserEdit(){
        if(request()->isAjax()){
            $params = input('param.');
            $data = [];
            if(empty($params['mechanism_member_password'])){
                unset($params['mechanism_member_password']);
            }else{
                $data['mechanism_member_password'] = md5($params['mechanism_member_password']);
            }
            $mechanismMemberModel = new MechanismMemberModel();
            $base64url = $params['mechanism_member_img'];
            //匹配出图片的格式
            $base64url = str_replace(' ', '+', $base64url);
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64url, $result)){
                $type = $result[2];
                $new_file = ROOT_PATH . 'public' . DS . 'uploads/face/'.date('Ymd',time())."/";
                if(!file_exists($new_file)){
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($new_file, 0700);
                }
                $new_file = $new_file.time().".{$type}";
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64url)))){
                    $new = md5(time());
                    //压缩图片
                    image_png_size_add($new_file,ROOT_PATH . 'public' . DS . 'uploads/face/'.date('Ymd',time())."/".$new.".{$type}");
                    $url =  "http://".$_SERVER['HTTP_HOST'];
                    $file_name = $url."/uploads/face/".date('Ymd',time())."/".$new.".{$type}";
                    $params['mechanism_member_img'] = $file_name;
                    //删除未压缩前图片
                    unlink($new_file);
                    //判断编辑的是不是自己的头像
//                    if(session('uid')==$params['id']){
//                        $have = "have";
//                    }else{
//                        $have = "";
//                    }
//                    return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg'],'type'=>$have]);
                }else{
                    return json(['code'=>100,'msg'=>"上传失败"]);
                }
            }
            $data['update_time'] = time();
            $flag = $mechanismMemberModel->editMechanismMember($params['id'], $data);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg'],'type'=>'']);
        }
        $mechanismModel = new MechanismModel();
        $mechanismMemberModel = new MechanismMemberModel();
        $id = input('param.id');
        $info = $mechanismMemberModel->getOneInfo($id);//获取机构管理员信息
    
        $ids = $this->mechanism_id;//获取本机构和下级机构的id
        $where['mechanism_id'] = ['IN', $ids];
        $mechanismInfo = $mechanismModel->getMechanismInfo($where);
        $mechanism_pid_id = Db::table('up_mechanism')->where('mechanism_id', session('mmid'))->value('mechanism_pid_id');
        $mechanismInfo = getCate($mechanismInfo, $mechanism_pid_id);//无限分类
        
        $this->assign([
            'mechanismInfo'  =>  $mechanismInfo,
            'info'  =>  $info
        ]);
        return $this->fetch('mechanismuser/mechanismuseredit');
    }
    
    /**
     * checkPhone 验证手机号的合法性
     */
    public function checkPhone(){
        $params = input('param.');
        if(!preg_match("/^1[345678]{1}\d{9}$/",$params['mechanism_member_phone'])){
            echo "false";
        }else{
            echo "true";
        }
    }
    
    /**
     * 机构管理员状态
     * @return \think\response\Json
     */
    public function mechanismMemberStatus(){
        $params = input('param.');
        $mechanismMemberModel = new MechanismMemberModel();
        $res = $mechanismMemberModel->mechanismMemberStatus($params['num'], $params['id']);
        return json(['code' => $res['code'], 'data' => $res['data'], 'msg' => $res['msg']]);
    }
    
    /**
     * 编辑机机构管理员密码
     * @return string|\think\response\Json
     */
    public function editPwd(){
        $params = input('param.');
        $mechanismMemberModel = new MechanismMemberModel();
        $data['mechanism_member_password'] = md5($params['new_pwd']);
        $res = $mechanismMemberModel->editMechanismMember(session('mid'), $data);
        if($res){
            return json(['code'=>200,'msg'=>'修改成功']);
        }else{
            return json(['code'=>100,'msg'=>'修改失败']);
        }
    }
    
    /**
     * 验证旧密码
     * @return string
     */
    public function checkOldpwd(){
        $params = input('param.');
        $mechanismMemberModel = new MechanismMemberModel();
        $info = $mechanismMemberModel->getOneInfo(session('mid'));
        if(md5($params['old_pwd']) != $info['mechanism_member_password']){//验证旧密码
            return 'false';
        }else{
            return 'true';
        }
    }
}